package de.akquinet.android.archetypes.tatt.view;


import de.akquinet.android.archetypes.tatt.R;
import de.akquinet.android.archetypes.tatt.control.UserControl;
import de.akquinet.android.archetypes.tatt.entity.User;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	User user= new User();

    /**
     * Called when the activity is first created.
     * @param savedInstanceState If the activity is being re-initialized after 
     * previously being shut down then this Bundle contains the data it most 
     * recently supplied in onSaveInstanceState(Bundle). <b>Note: Otherwise it is null.</b>
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        final EditText etUsername = (EditText) findViewById(R.id.usernameET);
		final EditText etPassword = (EditText) findViewById(R.id.passwordET);
		
		//This button open the application for the current teacher
		Button btnJumptoMenu = (Button) findViewById(R.id.loginBtn);
		btnJumptoMenu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String username, password;
				username= etUsername.getText().toString();
				password = etPassword.getText().toString();
				if(username.length() == 0 || password.length() == 0){
					Toast.makeText(LoginActivity.this, "Please indicate your username and password before log in", Toast.LENGTH_LONG).show();
				}
				else{
					// do the connection to database to get user 
					user = new User(username, password);
					UserControl userControl = new UserControl();
					
					
					if (userControl.login(user)){
						//Load main page for teacher taking attendance
						Intent teacherView = new Intent();
						teacherView.setClass(getApplicationContext(), TeacherActivity.class);
						
						startActivity(teacherView);
						Toast.makeText(LoginActivity.this, "Welcome "+username, Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(LoginActivity.this, "Authentication fails. Please try again.", Toast.LENGTH_LONG).show();
					}
				}	
				}
				
		});
		
		
		
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(de.akquinet.android.archetypes.tatt.R.menu.main, menu);
	
	return true;
    }

}

